import sqlalchemy
from fastapi import Request
from pydantic import BaseModel, Field

from .api_model.response_model import ApiResponse


async def get_message_list_api(request: Request, uid: str, engine):
    token_uid = request.state.user.get("uid")

    if not token_uid or token_uid != uid:
        print(token_uid)
        return ApiResponse(code=400, msg=f'{token_uid} 无权限查看 {uid} ')

    conn = engine.connect()
    try:
        result = conn.execute(sqlalchemy.text("""
                        SELECT message.sender_uid, user_info.username, message.send_time,
                         message.content, message.is_read, message.message_id
                        FROM message, user_info
                        WHERE message.receiver_uid = :uid AND message.sender_uid = user_info.uid
                    """), {
                "uid": uid
        })
        message_list = result.fetchall()
    except Exception as e:
        print(e)
        return ApiResponse(code=500, msg="查询消息列表信息发生错误")
    finally:
        conn.close()

    response = ApiResponse(code=200,
                           data={
                           },
                           msg="查询成功")
    response.data = {
        "uid": uid,
        "message_list": [
            {
                "sender_uid": message[0],
                "sender_username": message[1],
                "send_time": message[2],
                "content_summary": message[3][:10].replace('\n', ' ').replace('\r', ''),
                "content": message[3],
                "is_read": message[4],
                "message_id": message[5]
            } for message in message_list
        ]
    }
    return response


class SendMessageModel(BaseModel):
    receiver_uid: str = Field(..., min_length=3, max_length=50, description="手机号")
    content: str = Field(..., min_length=1)


async def send_message_api(request: Request, data: SendMessageModel, engine):
    token_uid = request.state.user.get("uid")
    sender = token_uid

    conn = engine.connect()
    try:
        conn.execute(sqlalchemy.text("""
                        INSERT INTO message (content, send_time, is_read, receiver_uid, sender_uid) 
                        VALUES (:content, NOW(), FALSE, :receiver_uid, :sender_uid)
                    """), {
                "sender_uid": sender,
                "receiver_uid": data.receiver_uid,
                "content": data.content,
        })
        conn.commit()
    except Exception as e:
        print(e)
        return ApiResponse(code=500, msg="发送失败")
    finally:
        conn.close()

    response = ApiResponse(code=200,
                           data={
                           },
                           msg="发送成功")
    return response


class SendClassMessageModel(BaseModel):
    class_name: str = Field(..., min_length=1, max_length=50, description="班级")
    content: str = Field(..., min_length=1)


async def send_class_message_api(request: Request, data: SendClassMessageModel, engine):
    token_uid = request.state.user.get("uid")
    sender = token_uid

    with engine.begin() as conn:
        try:
            conn.execute(sqlalchemy.text("""
                -- START TRANSACTION;
    
                INSERT INTO `message` (`content`, `send_time`, `is_read`, `receiver_uid`, `sender_uid`)
                SELECT 
                    :content AS `content`,
                    NOW() AS `send_time`,
                    FALSE AS `is_read`,
                    sd.uid AS `receiver_uid`,
                    :sender_uid AS `sender_uid` 
                FROM 
                    `stu_detail` sd
                WHERE 
                    sd.class_name = :class_name;
                
                -- COMMIT;
                        """), {
                    "sender_uid": sender,
                    "class_name": data.class_name,
                    "content": data.content,
            })

        except Exception as e:
            print(e)
            conn.rollback()
            return ApiResponse(code=500, msg="发送失败")

        response = ApiResponse(code=200,
                               data={
                               },
                               msg="发送成功")
        return response
